import React, { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { View, Image } from '@tarojs/components';
import { debounce } from '@/utils/helper';
import addImage from '@/images/common/add.png';
import subImage from '@/images/common/sub.png';
import subDisImage from '@/images/common/sub-disabled.png';
import ProductInfoLine from '../productInfoLine';
import './index.scss';

const Products = ({ products = {} }) => {
  const isMulti = products instanceof Array;
  return (
    <View>
      {isMulti ? (
        products.map((product) => {
          return <ProductInfoLine product={product} className="mb15" />;
        })
      ) : (
        <ProductInfoLine product={products} />
      )}
    </View>
  );
};

const ProductInfoAfterSale = ({ product = {}, className = '', title = '', handleNum = null }) => {
  const [num, setNum] = useState(handleNum ? 1 : product.hasRefundQuantity);

  const modifyNum = debounce((type) => {
    if (handleNum === null) {
      return;
    }
    switch (type) {
      case 'dec':
        if (num == 1) {
          Taro.showToast({
            title: '不能再少了~',
            duration: 2000,
            icon: 'none',
          });
          return;
        }
        setNum(num - 1);
        break;
      case 'inc':
        if (num == product.maxRefundQuantity) {
          Taro.showToast({
            title: '不能再多了~',
            duration: 2000,
            icon: 'none',
          });
          return;
        }
        setNum(num + 1);
        break;
      default:
        break;
    }
  }, 300);

  useEffect(() => {
    handleNum && handleNum(num);
  }, [num]);

  return (
    <View className={'productInfoAfterSale box2 ' + className}>
      <View className="txt32 black0 blod title">{title}</View>
      <Products products={product} />
      <View
        className={
          'applyNum ' +
          (handleNum !== null && product.maxRefundQuantity > 1
            ? 'flex-row-spaceBetween-center'
            : 'hidden')
        }
      >
        <View className="txt28">申请数量</View>
        <View className="number-sel">
          <View className="opBox flex-row-center-center" onClick={() => modifyNum('dec')}>
            <Image mode="widthFix" className="sub" src={num > 1 ? subImage : subDisImage} />
          </View>
          <View className="num">
            <View className="value">{num}</View>
          </View>
          <View className="opBox flex-row-center-center" onClick={() => modifyNum('inc')}>
            <Image mode="widthFix" className="add" src={addImage} />
          </View>
        </View>
      </View>
    </View>
  );
};

export default ProductInfoAfterSale;
